package top.lgd.service.operation;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.lgd.base.LgdConstants;
import top.lgd.base.LgdException;
import top.lgd.enums.AccontFlowTypeEnum;
import top.lgd.mapper.operation.MemberMapper;
import top.lgd.pojo.entity.operation.Member;
import top.lgd.pojo.entity.operation.MemberFlow;
import top.lgd.pojo.req.operation.MemberOpReq;
import top.lgd.service.LgdCacheService;
import top.lgd.utils.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;

/**
 * 系统用户表 服务实现类
 *
 * @author YYJ
 * @version 1.0
 * @since 2023/12/15 10:10
 */
@Service
public class MemberService extends ServiceImpl<MemberMapper, Member> implements IService<Member> {

    @Autowired
    private MemberFlowService memberFlowService;
    @Autowired
    private LgdCacheService lgdCacheService;

    /**
     * 【有缓存】
     *
     * @param id
     * @return
     */
    public Member queryMember(Long id) {
        Member member = null;
        if (null != id) {
            String key = LgdConstants.KEY_OPERATION_MEMBER_INFO + id;
            member = lgdCacheService.get(key);
            if (null != member) {
                return member;
            }

            member = getById(id);
            if (null != member) {
                lgdCacheService.put(key, member);
            }
        }
        return member;
    }

    /**
     * 【有缓存】
     *
     * @param userId
     * @return
     */
    public Member queryMember(Long userId, String mobile) {
        Member member = null;
        if (StringUtils.isNotEmpty(mobile)) {
            String key = LgdConstants.KEY_OPERATION_MEMBER_INFO + userId + "-" + mobile;
            member = lgdCacheService.get(key);
            if (null != member) {
                return member;
            }

            member = getOne(new QueryWrapper<Member>().eq(LgdConstants.COLUMN_DATA_USER_ID, userId)
                    .eq(LgdConstants.COLUMN_MOBILE, mobile).last(LgdConstants.SQL_LIMIT + 1));
            if (null != member) {
                lgdCacheService.put(key, member);
            }
        }
        return member;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean addUpdateAndFlow(Member member) {
        member.setBalance(member.getInAmount());
        if (null != member.getId()) {
            clearCache(member.getId(), member.getDataUserId(), member.getMobile());
            return updateById(member);
        }

        if (save(member)) {
            if (member.getInAmount().compareTo(BigDecimal.ZERO) > 0) {
                MemberFlow memberFlow = new MemberFlow();
                memberFlow.setMemberId(member.getId());
                memberFlow.setFlowDate(LocalDate.now());
                memberFlow.setFlowType(AccontFlowTypeEnum.IN.name());
                memberFlow.setFlowAmount(member.getInAmount());
                memberFlow.setAfterAmount(member.getBalance());
                memberFlow.setRemark("会员开卡首充");
                memberFlowService.save(memberFlow);
            }
            clearCache(member.getId(), member.getDataUserId(), member.getMobile());
            return true;
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean opAndFlow(Member member, MemberOpReq memberOpReq) {
        if (memberOpReq.getOpAmount().compareTo(BigDecimal.ZERO) > 0) {
            MemberFlow memberFlow = new MemberFlow();
            memberFlow.setMemberId(member.getId());
            memberFlow.setFlowDate(LocalDate.now());
            memberFlow.setFlowType(memberOpReq.getOpType());
            memberFlow.setFlowAmount(memberOpReq.getOpAmount());
            if (AccontFlowTypeEnum.IN.name().equals(memberOpReq.getOpType())) {
                memberFlow.setBeforeAmount(member.getBalance());
                memberFlow.setAfterAmount(member.getBalance().add(memberOpReq.getOpAmount()));
                memberFlow.setRemark("充值：" + memberOpReq.getOpAmount() + "元");
                member.setInAmount(member.getInAmount().add(memberOpReq.getOpAmount()));
            } else if (AccontFlowTypeEnum.OUT.name().equals(memberOpReq.getOpType())) {
                if(memberOpReq.getOpAmount().compareTo(member.getBalance())>0){
                    throw new LgdException("余额不足");
                }
                memberFlow.setBeforeAmount(member.getBalance());
                memberFlow.setAfterAmount(member.getBalance().add(memberOpReq.getOpAmount()));
                memberFlow.setRemark("消费：" + memberOpReq.getOpAmount() + "元");
                member.setOutAmount(member.getOutAmount().add(memberOpReq.getOpAmount()));
            }
            memberFlowService.save(memberFlow);
        }
        member.setBalance(member.getInAmount().subtract(member.getOutAmount()));
        clearCache(member.getId(), member.getDataUserId(), member.getMobile());
        return updateById(member);
    }

    private void clearCache(Long id, Long userId, String mobile) {
        lgdCacheService.delete(LgdConstants.KEY_OPERATION_MEMBER_INFO + id);
        lgdCacheService.delete(LgdConstants.KEY_OPERATION_MEMBER_INFO + userId + "-" + mobile);
    }
}